/******************************************************************************

  File Name     : mp_common.c
  Version       : Initial Draft
  Author        : tongzhilin
  Created       : 2020/8/6
  Last Modified :
  Description   : mp_common
  Function List :
  History       :
  1.Date        : 2020/8/6
    Author      : tongzhilin
    Modification: Created file

******************************************************************************/
#include "mp_common.h"

#define NANOSECOND                      1000000000
#define MICROSECOND                     1000000
#define MILLISECOND                     1000

INT32 mp_sleep_us(UINT32 us)
{
    INT32 ret = 0;

    ret = usleep(us);

    return ret;
}

INT32 mp_sleep_ms(UINT32 ms)
{
    INT32 ret = 0;

    ret = usleep(ms * MILLISECOND);

    return ret;
}

INT32 mp_sleep_s(UINT32 s)
{
    INT32 ret = 0;

    ret = mp_sleep_ms(s * MILLISECOND);

    return ret;
}

UINT64 mp_getmillisecond(void)
{
    struct timeval time_v = { 0 };
    gettimeofday(&time_v, NULL);

    return (UINT64)time_v.tv_sec * 1000 + time_v.tv_usec / 1000;
}

UINT64 mp_getrelativems(VOID)
{
    INT32 ret = -1;
    struct timespec time = { 0 };

    ret = clock_gettime(CLOCK_MONOTONIC_RAW, &time);
    if (ret)
    {
        return 0;
    }

    return (UINT64)time.tv_sec * 1000 + time.tv_nsec / 1000000;
}


static INT32 mp_do_printf(const char *fmt, va_list args)
{
    INT32 ret = 0;
    INT32 output = 1;
    UINT64 u64Time = 0;
    char fmtbuf[8192] = { 0 };
    char msgbuf[8192] = { 0 };

    u64Time = mp_getmillisecond();
    struct tm ptm_now;

    time_t now = u64Time/1000;
    INT32 time_ms = u64Time%1000;
    localtime_r(&now, &ptm_now);

    snprintf(fmtbuf, sizeof(fmtbuf), GREEN "[%04d/%02d/%02d %02d:%02d:%02d-%04d]" NONE ": %s", 
        ptm_now.tm_year+1900,
        ptm_now.tm_mon+1,
        ptm_now.tm_mday,
        (ptm_now.tm_hour)%24,
        ptm_now.tm_min,
        ptm_now.tm_sec, 
        time_ms,
        fmt);
    vsnprintf(msgbuf, sizeof(msgbuf), fmtbuf, args);

    ret = write(output, msgbuf, strlen(msgbuf));
    return ret;
}

void mp_printf(const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    mp_do_printf(fmt, args);
    va_end(args);

    return;
}

